#!/usr/bin/env python
# $Id: add_upc_type.py 2 2008-04-04 18:53:47Z benchline $

from page import page
import sys, urllib
import db 

class add(page):

	def __init__(self):
		page.__init__(self)
		self.headingstr = "Add Custom UPC"
		self.db1 = db.db()
		self.upcdb1 = db.upcdb()

	def get_var(self, var, default=""):
		if request.has_key(var):
			return request[var][0]
		else:
			return default

	def render(self):
		self.logic()
		self.encoding()
		self.html()

	def add_upc_type(self):
		upc = request["upc"][0]
		amt = request["amt"][0]
		amt, unit = amt.split()
		typeid = request["typeid"][0]
		desc = request["desc"][0].replace("'", "")
		if not self.db1.upc_type_there(upc):
			self.db1.add_upc_type(upc, typeid, amt, unit, desc)
			msg = "The '%s' upc type has been added" % upc
			self.log(msg)
		else:
			msg = "There is already a upc type for %s" % upc
			self.log(msg)
		return msg

	def logic(self):
		if request.has_key("cancel"):
			raise HTTP_REDIRECTION, "menu.py"
		if request.has_key("submit"):
			msg = self.add_upc_type()
			raise HTTP_REDIRECTION, "add_upc_type.py?%s" % urllib.urlencode({"m":msg})

	def form(self):
		form = """
		<form name="add" method="GET" action="add_upc_type.py">
		<table style="text-align: left; width: 20%;" border="0" cellpadding="2" cellspacing="2">
		<tbody>
		<tr>
			<td>Type</td>
			<td>"""
		print form
		print "<select name=typeid>"
		types = self.db1.get_type_list()
		for type in types:
			id, desc = type
			print "\t<option value=%s>%s</option>" % (id, desc)
		print "</select>"
		form = """</td>
		</tr>
		<tr>
			<td>UPC</td>
			<td><input type=text name=upc value="%s"></td>
		</tr>
		<tr>
			<td>Description</td>
			<td><input type=text name=desc value="%s"></td>
		</tr>
		<tr>
			<td>Amount and Unit</td>
			<td><input type=text name=amt value="%s"></td>
		</tr>
		<tr>
			<td><input name=submit type=submit value="Submit"></td>
			<td><input type=submit name=cancel value="Menu"></td>
		</tr>
		<script>document.forms.add.typeid.focus();</script>
		</tbody>
		</table>
		</form>
		""" % (self.get_var("upc"), self.get_var("desc"), self.get_var("amt"))
		print form

	def body(self):
		self.start_body()
		self.heading()
		self.form()
		self.message()
		self.footer()
		self.end_body()

	def message(self):
		if request.has_key("m"):
			message = request["m"][0]
			if message:
				print message

class runner:
	def _test(self):
		add().render()

	def _doctest(self):
		import doctest
		doctest.testmod()

if __name__ == "__main__":
	r = runner()
	getattr(r, "_"+sys.argv[1])()
else:
	add().render()
